let layerIndex;
let $;
var toast;

/*
* 弹出新增/更新对话框
* */
function showStudentDlg(id) {
    //重启提交按钮
    $("#btnOK").prop("disabled", false).removeClass("layui-btn-disabled");
    let title = "新增学生"
    if (id) {
        //更新
        title = "编辑学生";
        $("#formId").css("display", "block");

        //读取学生信息并赋值
        $.ajax({
            url: "/api/student/" + id,
            method: "GET",
        }).done(result => {
            console.log(result)
            if (result.code >= 0) {
                $.each(result.data, function (key, value) {
                    var filed = $('#studForm [name = "' + key + '"]');
                    if (filed.is(":radio")) {
                        filed.filter('[value = "' + value + '"] ').prop("checked", true);
                    } else if (filed.is(":checkbox")) {
                        filed.prop("checked", value === 'yes');
                    } else {
                        filed.val(value);
                    }
                })

                //再次渲染表单，确保内容更新
                layui.form.render();
            } else {
                toast.error({
                    message: result.msg
                });
            }
        })
    } else {
        //新增
        $("#studForm")[0].reset();
        $("#formId").css("display", "none");
    }
    layerIndex = layer.open(
        {
            type: 1,
            title: title,
            area: ['400px', 'auto'],
            content: $('#popDlg')[0].innerHTML,  //解决admin系统自身问题
            // end: function () {
            //     // 弹窗关闭时隐藏表单
            //     $('#studForm').hide();
            // }
        }
    )
    console.log(layerIndex)

}

/**
 * 获得搜索条件
 * @returns {{}}
 */
function getSearchCondition() {
    //获取数据
    let formData = {}
    $("#queryForm").find("input,select").each(function () {
        let name = $(this).attr("name");
        let value = $(this).val();

        if (name && value) {
            formData[name] = value;
        }
    });

    return formData;
}

layui.use(['form', 'table'], function () {
    $ = layui.$
    toast = layui.toast
    const form = layui.form;
    // 确保表单渲染
    form.render();
    //验证表单是否合法
    form.on('submit(stud-dlg)', function (data) {
        event.preventDefault(); //阻止表单默认提交
        // commitStuDlg();
        //防止重复提交
        if(this.isSumitting) return false;
        this.isSumitting = true;
        commitStuDlg()
            .catch(error=>{
                console.error("提交错误",error);
            })
            .finally(()=>{
                this.isSumitting = false;
            });
        return false; //阻止事件冒泡
    })

    //表格初始化
    const table = layui.table;
    let student = getSearchCondition();

    //渲染
    table.render({
        elem: "#tbStudent",
        url: "/api/student/getbypage",
        method: "POST",
        contentType: "application/json",
        where: {"data": student},
        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', fixed: 'left', width: 80, title: 'id', sort: true},
            {field: 'name', title: '姓名'},
            {field: 'sno', title: '学号', width: 150},
            {
                field: 'sex', width: 80, title: '性别', sort: true,
                templet: d => d.sex === 1 ? '女' : (d.sex === 2 ? '男' : '未知'),
            },
            {field: 'age', width: 100, title: '年龄', sort: true},
            {fixed: 'right', title: "操作", width: 134, minWidth: 125, templet: "#editTemplate"}
        ]],
        done: function (rs) {
            console.log(rs)
        }
    })

    //触发单元格事件
    table.on('tool(tbStudent)', function (obj) {
        var data = obj.data
        if (obj.event === 'edit') {
            //点击编辑后显示弹出层
            showStudentDlg(data.id);
        }
    });
});

/**
 * 搜索功能
 */
function search() {
    let student = getSearchCondition();
    const table = layui.table;
    table.reload("tbStudent", {
        where: {data: student},
        page: {curr: 1} // 重置到第一页
    });
    console.log("where condition :" + JSON.stringify(student))
}

/**
 * 批量删除操作
 */
function deleteConfrim() {
    const table = layui.table;
    const checkStatus = table.checkStatus('tbStudent');// 获取选中行数据
    console.log(checkStatus);
    const selectedData = checkStatus.data; // 选中的数据

    if (selectedData.length === 0) {
        layer.msg('请至少选择一条数据', {icon: 2}); // 提示未选择数据
        return;
    }

    // 提取所有选中的学生ID
    const ids = selectedData.map(item => item.id);

    layer.confirm('确定要删除这 ' + selectedData.length + ' 条数据吗？删除后不可恢复！', {icon: 3}, function () {
        $.ajax({
            url: "/api/student/deletebatch",
            method: "DELETE",
            contentType: "application/json",
            data: JSON.stringify(ids) // 传递ID数组
        }).done(result => {
            if (result.code === 0) {
                layer.msg('删除成功', {icon: 1});
                search(); // 刷新表格
            } else {
                layer.msg('删除失败: ' + result.message, {icon: 2});
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("删除失败:", textStatus, errorThrown);
            layer.msg('删除失败，请稍后重试', {icon: 2});
        });
    });
}

/**
 * 提交操作
 */
function commitStuDlg() {
    //异步提交操作
    return new Promise((resolve, reject)=>{
        $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");//禁用按钮
        const currentLayerIndex = layerIndex;
        //获取表单信息
        let formData = {};
        $("#studForm").serializeArray().forEach(item => {
            formData[item.name] = item.value;
        });
        const id = formData.id
        const url = id? "/api/student/update" : "/api/student/add";
        const method = id? "PUT" : "POST";

        $.ajax({
            url: url,
            method: method,
            contentType: "application/json",
            data: JSON.stringify(formData)
        }).done(result => {
            if (result.code >= 0 && result.data?.id) {
                //读取并刷新学生列表
                search();

                //关闭弹出层
                console.log("add success!")
                if (currentLayerIndex)
                    layer.close(currentLayerIndex)
                resolve(result);
            } else {
                //处理业务逻辑错误
                const errorMsg = result.msg || (id ? "更新失败" : "新增失败，没有返回id");
                toast.error({
                    message: result.msg
                });
                reject(new Error(errorMsg));
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            const errorMsg = `请求失败: ${textStatus} - ${errorThrown}`
            console.error(errorMsg);
            //可以在这里处理错误逻辑
            alert("错误信息，请稍后重试");
            reject(new Error(errorMsg));
        }).always(()=>{
            $("#btnOK").prop("disabled", true).removeClass("layui-btn-disabled");//禁用按钮
        })
    });

}